//
//  ZTacticsDetailViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/2/23.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "ZTacticsDetailViewController.h"
#import "ZPostCommentView.h"// 发表评论一栏
#import "ZDoctorHeadCell.h"
#import "ZCommentTableViewCell.h"
#import "ZDiscussViewController.h"// 评论详情界面
#import "TacticsDetailModel.h"
#import "SPPlaceholderCell.h"
static NSString *const placeCellID = @"placeholders";
static NSString * const ZTacticsDetailDoctorHeadCellIdentifier = @"ZTacticsDetailDoctorHeadCellIdentifier";
static NSString * const ZTacticsDetailCommentTableViewCellIdentifier = @"ZTacticsDetailCommentTableViewCellIdentifier";
@interface ZTacticsDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UIWebViewDelegate>{
    UIWebView * _headWebView;
    ZPostCommentView * _postView;
    UITableView * _mainTabView;
    NSInteger  _WebViewHeight;
    LZUserInfo *userInfo;
    TacticsDetailModel * _tacticsDetailItem;
}
/** 评论数据数组 */
@property (nonatomic, strong) NSMutableArray <TacticsDetailModel *>*commentArr;
@property (nonatomic,assign) BOOL isHaveData;


@end

@implementation ZTacticsDetailViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialzeDatas];
    [self initlizeInterface];
    _commentArr = [NSMutableArray array];
    userInfo = [LZUserInfo getUserInfo];
     [_mainTabView.mj_header beginRefreshing];
}
- (void)setArtId:(NSString *)artId {
    _artId = artId;
   
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([userInfo.uid isEqualToString:@""] || userInfo.uid == nil) {
        [self remakeConstraints];
    }else {
        [self appearComment];
    }
}
// 修改tableView和评论栏的约束（游客模式）
- (void)remakeConstraints {
    [_mainTabView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    _postView.hidden = YES;
}
// 登录模式显示评论栏
- (void)appearComment {
    _mainTabView.frame = CGRectMake(0, 0,SCREEN_Width, SCREEN_Height-129*ysIZE);
    _postView.hidden = NO;
}

- (void)initialzeDatas {
    _WebViewHeight = 200; // 设置默认高度最后修改;
    self.isHaveData = YES;
}

- (void)initlizeInterface {
    self.navigationItem.title = @"就医策略";
    self.view.backgroundColor = [UIColor whiteColor];
    _headWebView = [[UIWebView alloc] init];
    _headWebView.frame = CGRectMake(0, 0, SCREEN_Width, _WebViewHeight);
    _headWebView.userInteractionEnabled = NO;//关闭交互
    _headWebView.delegate = self;
    //创建发布评论一栏
    _postView = [[ZPostCommentView alloc] init];
    [_postView.postBtn  addTarget:self action:@selector(postCommet) forControlEvents:UIControlEventTouchUpInside];
    
    _mainTabView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,SCREEN_Width, SCREEN_Height-129*ysIZE) style:UITableViewStylePlain];
    _mainTabView.delegate = self;
    _mainTabView.dataSource = self;
    _mainTabView.separatorStyle = 0;
    _mainTabView.showsVerticalScrollIndicator = NO;
    [_mainTabView registerClass:[ZDoctorHeadCell class] forCellReuseIdentifier:ZTacticsDetailDoctorHeadCellIdentifier];
    [_mainTabView registerNib:[UINib nibWithNibName:NSStringFromClass([SPPlaceholderCell class]) bundle:nil] forCellReuseIdentifier:placeCellID];
    [_mainTabView registerClass:[ZCommentTableViewCell class] forCellReuseIdentifier:ZTacticsDetailCommentTableViewCellIdentifier];
    _mainTabView.tableHeaderView = _headWebView;
    
    // 下拉刷新
    __weak typeof(self) weakSelf = self;
    _mainTabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf pullDownData];
        [_mainTabView.mj_header endRefreshing];
    }];
    
    [self.view addSubview:_mainTabView];
    [self.view addSubview:_postView];
    [_postView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.bottom.equalTo(self.view);
        make.height.offset(65*ysIZE);
    }];
    
    
}
// 表格视图协议
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else{
//        if (_commentArr.count <= 5) {
//            return _commentArr.count;
//        }else {
//            return 5;
//        }
        return self.isHaveData == YES ? _commentArr.count : 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 40*ysIZE;
    }else{
        if (self.isHaveData == YES) {
        return 70*ysIZE;
    }else {
        return  SCREEN_Height-404;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ZDoctorHeadCell * cell = [tableView dequeueReusableCellWithIdentifier:ZTacticsDetailDoctorHeadCellIdentifier forIndexPath:indexPath];
        cell.selectionStyle = 0;
        
        // 判断名字是否有
        if (_commentArr) {
            NSString *nameStr = [NSString stringWithFormat:@"%lu%@",(unsigned long)_commentArr.count,@"条回复"];
            cell.midTitleLabel.text = nameStr;
        }
        return cell;
    }else {
        if (self.isHaveData == YES) {
            ZCommentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ZTacticsDetailCommentTableViewCellIdentifier forIndexPath:indexPath];
            if(indexPath.row < _commentArr.count) {
                cell.tacticsDetailModel = _commentArr[indexPath.row];
            }
            cell.selectionStyle = 0;
            return cell;
        }else {
                SPPlaceholderCell *cell = [tableView dequeueReusableCellWithIdentifier:placeCellID];
                return cell;

        }
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isHaveData == NO) {
        return;
    }
    if (indexPath.section == 0 ) {
        ZDiscussViewController * ZDVC = [[ZDiscussViewController alloc] init];
        ZDVC.artID = self.artId;
        [self.navigationController pushViewController:ZDVC animated:YES];
    }
}
// 发布按钮的方法
- (void)postCommet {
    if ([_postView.commentField.text isEqualToString:@""]) {
        [YJProgressHUD showMessage:@"评论不可以为空~" inView:self.view];
        return;
    }
    // 引号转换
    NSString * comText = [_postView.commentField.text stringByReplacingOccurrencesOfString:@"\"" withString:@"”" ];
    
    NSDictionary *paramas = @{@"id":_artId,@"uid":userInfo.uid,@"content":comText};
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Index/addArticleCmt" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"就医策略详情发表评论数据----%@",dict);
        if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"评论成功" inView:self.view];
            // 评论textfield失去第一响应并且刷新数据
            _postView.commentField.text = @"";
            [_postView.commentField resignFirstResponder];
            [_mainTabView.mj_header beginRefreshing];
            
        }else if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"评论失败" inView:self.view];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"评论失败" inView:self.view];
    }];
    
}
// webView协议
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    CGRect frame = webView.frame;
    NSInteger height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] integerValue];
    [UIView animateWithDuration:0.01 animations:^{
        webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height) ;
        webView.userInteractionEnabled = NO;
        if (_WebViewHeight == height + 50) {
            return;
        }
        _WebViewHeight = height + 50;
        [_mainTabView reloadData];
    }];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 下拉刷新
- (void)pullDownData {
    [YJProgressHUD showProgress:@"努力加载中..." inView:self.view];
    [_commentArr removeAllObjects];
    NSDictionary *paramas = @{@"id":_artId};
    __weak typeof(self) weakSelf = self;
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Index/articleCmtList" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"就医策略详情----%@",dict);
        if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"刷新成功" inView:self.view];
            NSString *urlStr = [NSString stringWithFormat:@"%@%@",TestURL,dict[@"url"]];
            [_headWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
            [weakSelf setValueWithDict:dict];
        }else  {
            self.isHaveData = NO;
            [_mainTabView reloadData];
            [YJProgressHUD showMessage:@"刷新失败" inView:self.view];
        }
    } failure:^(NSError *error) {
            self.isHaveData = NO;
        [_mainTabView reloadData];
        [YJProgressHUD showMessage:@"刷新失败" inView:self.view];
    }];
}

// 取出数据模型加入到模型数组中
- (void)setValueWithDict:(NSDictionary *)dict {
    [_commentArr removeAllObjects];
    NSArray * dataArray = dict[@"list"];
    if (dataArray.count == 0) {
        self.isHaveData = NO;
    }
    for (NSDictionary *dict in dataArray) {
        TacticsDetailModel *tacticsDetailItem = [[TacticsDetailModel alloc] initWithDict:[dict mutableCopy]];
        _tacticsDetailItem = tacticsDetailItem;
        [_commentArr addObject:_tacticsDetailItem];
    }
    [_mainTabView reloadData];
}

//// 上拉加载
//- (void)loadMoreData {
//    _page++;
//    [YJProgressHUD showProgress:@"努力加载中..." inView:self.view];
//    NSDictionary *paramas = @{@"id":_artId};
//    __weak typeof(self) weakSelf = self;
//    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Index/articleCmtList" sucessBlock:^(id content) {
//        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
//        LZLog(@"就医策略详情上拉数据----%@",dict);
//        if ([dict[@"code"] intValue] == 1) {
//            [YJProgressHUD showMessage:@"加载成功" inView:self.view];
//            [weakSelf dealDataWithDict:dict];
//            //[weakSelf setValueWithDict:dict];
//        }else if ([dict[@"code"] intValue] == 0) {
//            [YJProgressHUD showMessage:@"刷新失败" inView:self.view];
//        }
//    } failure:^(NSError *error) {
//        LZLog(@"%@",error);
//    }];
//}
//
//// 上拉加载以后处理数据
//- (void)dealDataWithDict:(NSDictionary *)dict {
//    NSArray * dataArray = dict[@"list"];
//    if (dataArray.count == 0) {
//        [YJProgressHUD showMessage:@"没有更多数据了~" inView:self.view];
//        [_mainTabView.mj_footer endRefreshingWithNoMoreData];
//        [_mainTabView reloadData];
//        return;
//    }else if (dataArray.count < 5) {
//        [_mainTabView.mj_footer endRefreshingWithNoMoreData];
//    }
//    for (NSDictionary *dict in dataArray) {
//        TacticsDetailModel *tacticsDetailItem = [[TacticsDetailModel alloc] initWithDict:[dict mutableCopy]];
//        [_commentArr addObject:tacticsDetailItem];
//    }
//    [_mainTabView reloadData];
//}

@end
